package com.lms.demo.fileservice.service.impl;

import com.lms.demo.autoconfigure.minio.MinioTemplate;
import com.lms.demo.fileservice.mapper.FileInfoMapper;
import com.lms.demo.fileservice.model.FileInfo;
import com.lms.demo.fileservice.service.FileService;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;


/**
 * @Author: 李孟帅
 * @CreateTime: 2020-12-24 11:44
 * @Description:
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Autowired
    private MinioTemplate minioTemplate;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String upload(MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        String fileId = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        long size = file.getSize();
        //将文件信息上传到数据库中
        FileInfo fileInfo = new FileInfo()
                .setFileId(fileId)
                .setFilename(filename)
                .setSize(size);
        fileInfoMapper.insert(fileInfo);
        //将文件数据上传到对象存储中
        InputStream inputStream = file.getInputStream();
        minioTemplate.uploadObjectByInputStream("filetest",fileId, inputStream);
        inputStream.close();
        return fileId;
    }
}
